

<template>
  <div class="annual-plans-container">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <!-- 左侧筛选和搜索 -->
      <div class="filter-section">
        <el-select 
          v-model="filterYear" 
          placeholder="筛选年份" 
          clearable
          style="width: 150px;"
          @change="applyFilters"
        >
          <el-option label="全部年份" value="" />
          <el-option 
            v-for="year in availableYears" 
            :key="year" 
            :label="`${year}年`" 
            :value="year" 
          />
        </el-select>
        
        <el-select 
          v-model="filterStatus" 
          placeholder="筛选状态" 
          clearable
          style="width: 150px;"
          @change="applyFilters"
        >
          <el-option label="全部状态" value="" />
          <el-option label="待开始" value="pending" />
          <el-option label="进行中" value="in_progress" />
          <el-option label="已完成" value="completed" />
        </el-select>
        
        <el-input 
          v-model="searchTitle" 
          placeholder="搜索计划标题..."
          prefix-icon="Search"
          clearable
          style="width: 250px;"
          @input="applyFilters"
        />
      </div>
      
      <!-- 右侧操作按钮 -->
      <div class="action-buttons">
        <el-button-group>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon> 创建计划
          </el-button>
          <el-button type="success" @click="showAISuggestionDialog = true">
            <el-icon><MagicStick /></el-icon> AI建议
          </el-button>
        </el-button-group>
        
        <!-- 批量操作按钮 -->
        <el-dropdown 
          v-if="selectedPlans.length > 0"
          @command="handleBatchCommand"
          split-button
          type="warning"
          @click="batchUpdateStatus('completed')"
        >
          批量操作 ({{ selectedPlans.length }})
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="complete" icon="Select">
                标记为已完成
              </el-dropdown-item>
              <el-dropdown-item command="in_progress" icon="Loading">
                标记为进行中
              </el-dropdown-item>
              <el-dropdown-item command="pending" icon="Clock">
                标记为待开始
              </el-dropdown-item>
              <el-dropdown-item divided command="delete" icon="Delete">
                <span style="color: #F56C6C;">批量删除</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 空状态提示 -->
    <el-empty 
      v-if="!loading && filteredPlans.length === 0 && annualPlans.length === 0" 
      description="还没有年度计划，点击按钮创建第一个计划吧！"
      :image-size="200"
    >
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon> 创建第一个年度计划
      </el-button>
    </el-empty>
    
    <!-- 无搜索结果提示 -->
    <el-empty 
      v-else-if="!loading && filteredPlans.length === 0 && annualPlans.length > 0" 
      description="没有找到匹配的计划"
      :image-size="150"
    >
      <el-button @click="clearFilters">清除筛选条件</el-button>
    </el-empty>

    <!-- 数据表格 -->
    <el-table 
      v-else
      :data="filteredPlans" 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDblClick"
      stripe
      :default-sort="{ prop: 'year', order: 'descending' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="year" label="年份" width="100" sortable />
      <el-table-column prop="title" label="计划标题" width="200" />
      <el-table-column prop="description" label="描述" width="300">
        <template #default="{ row }">
          <div class="text-content" :title="row.description">
            {{ row.description && row.description.length > 50 ? row.description.substring(0, 50) + '...' : row.description }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="objectives" label="目标摘要" width="300">
        <template #default="{ row }">
          <div class="text-content" :title="row.objectives">
            {{ row.objectives && row.objectives.length > 80 ? row.objectives.substring(0, 80) + '...' : row.objectives }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" sortable>
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)" effect="dark">
            <el-icon v-if="row.status === 'pending'"><Clock /></el-icon>
            <el-icon v-else-if="row.status === 'in_progress'"><Loading /></el-icon>
            <el-icon v-else><SuccessFilled /></el-icon>
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180" sortable>
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="420" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="viewPlanDetail(row)" icon="View">查看</el-button>
          <el-button size="small" @click="editPlan(row)" icon="Edit">编辑</el-button>
          <el-button 
            size="small" 
            type="success"
            @click="generateMonthlyPlansForAnnual(row)"
            icon="MagicStick"
          >
            月度建议
          </el-button>
          <el-button 
            size="small" 
            :type="row.status === 'completed' ? 'warning' : 'success'"
            @click="toggleStatus(row)"
          >
            {{ row.status === 'completed' ? '未完成' : '完成' }}
          </el-button>
          <el-button size="small" type="danger" @click="deletePlan(row)" icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Create/Edit Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingPlan ? '编辑年度计划' : '创建年度计划'"
      width="500px"
    >
      <el-form :model="planForm" :rules="rules" ref="planFormRef" label-width="100px">
        <el-form-item label="年份" prop="year">
          <el-input-number v-model="planForm.year" :min="2020" :max="2030" />
        </el-form-item>
        <el-form-item label="计划标题" prop="title">
          <el-input v-model="planForm.title" placeholder="请输入计划标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="planForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入计划描述"
          />
        </el-form-item>
        <el-form-item label="目标" prop="objectives">
          <el-input 
            v-model="planForm.objectives" 
            type="textarea" 
            :rows="4"
            placeholder="请输入年度目标"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPlan" :loading="submitting">
          {{ editingPlan ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- AI 建议对话框 -->
    <el-dialog
      v-model="showAISuggestionDialog"
      title="AI 年度计划建议"
      width="600px"
    >
      <el-alert
        v-if="aiSuggestionError"
        :title="aiSuggestionError"
        type="warning"
        show-icon
        closable
        style="margin-bottom: 20px;"
      />
      <el-form :model="aiSuggestionForm" label-width="100px">
        <el-form-item label="工作目标">
          <el-input 
            v-model="aiSuggestionForm.goal" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述您的工作目标和期望达成的成果..."
          />
        </el-form-item>
        
        <el-form-item label="关键指标">
          <el-input 
            v-model="aiSuggestionForm.keyMetrics" 
            type="textarea" 
            :rows="3"
            placeholder="请列出可量化的关键指标（如：销售额增长20%，客户满意度达到90%等）"
          />
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="aiSuggestionForm.timeframe"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAISuggestionDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateAISuggestion" 
          :loading="generatingAISuggestion"
        >
          <el-icon><MagicStick /></el-icon>
          生成AI建议
        </el-button>
      </template>
    </el-dialog>

    <!-- AI 建议确认对话框 -->
    <el-dialog
      v-model="showAIConfirmDialog"
      title="AI 建议确认"
      width="800px"
    >
      <div v-if="aiSuggestionResult" class="ai-confirm-content">
        <!-- 流式生成进度条 -->
        <div v-if="isGeneratingStream" style="margin-bottom: 20px;">
          <el-progress 
            :percentage="Math.round((generationProgress / generationTotal) * 100)" 
            :status="generationProgress === generationTotal ? 'success' : ''"
            :stroke-width="15"
            striped
            striped-flow
          />
          <div style="text-align: center; margin-top: 10px; color: #606266; font-size: 14px;">
            <el-icon class="is-loading" v-if="generationProgress < generationTotal" style="margin-right: 5px;"><Loading /></el-icon>
            {{ generationStatus }}
          </div>
        </div>

        <h4 v-if="aiSuggestionResult.annualPlan">年度计划建议</h4>
        <el-descriptions v-if="aiSuggestionResult.annualPlan" :column="1" border>
          <el-descriptions-item label="计划标题">
            {{ aiSuggestionResult.annualPlan.title }}
          </el-descriptions-item>
          <el-descriptions-item label="年度目标">
            {{ aiSuggestionResult.annualPlan.objective }}
          </el-descriptions-item>
          <el-descriptions-item label="战略措施">
            <ul>
              <li v-for="strategy in aiSuggestionResult.annualPlan.strategies" :key="strategy">
                {{ strategy }}
              </li>
            </ul>
          </el-descriptions-item>
          <el-descriptions-item label="预期成果">
            <ul>
              <li v-for="outcome in aiSuggestionResult.annualPlan.expectedOutcomes" :key="outcome">
                {{ outcome }}
              </li>
            </ul>
          </el-descriptions-item>
        </el-descriptions>

        <h4 style="margin-top: 20px;">月度计划概览</h4>
        <el-table :data="aiSuggestionResult.monthlyPlans" height="400" stripe>
          <el-table-column prop="month" label="月份" width="100" fixed />
          <el-table-column prop="mainObjective" label="主要目标" min-width="200">
            <template #default="{ row }">
              {{ row.mainObjective || row.title }}
            </template>
          </el-table-column>
          <el-table-column prop="tasks" label="任务数量" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small" type="info">{{ row.tasks?.length || 0 }} 个任务</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="关键指标" min-width="200">
            <template #default="{ row }">
              <div v-if="row.metrics && row.metrics.length">
                <div v-for="(metric, idx) in row.metrics" :key="idx" style="font-size: 12px; line-height: 1.4;">
                  • {{ metric.name }}: {{ metric.target }}
                </div>
              </div>
              <div v-else-if="row.keyMetrics">
                {{ row.keyMetrics.join('，') }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="regenerateAISuggestion">重新生成</el-button>
        <el-button type="primary" @click="confirmAISuggestion">确认使用</el-button>
      </template>
    </el-dialog>

    <!-- 查看年度计划详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="年度计划详情"
      width="700px"
    >
      <div v-if="currentViewPlan">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="年份">{{ currentViewPlan.year }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentViewPlan.status)" effect="dark">
              {{ getStatusText(currentViewPlan.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="计划标题" :span="2">
            {{ currentViewPlan.title }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDate(currentViewPlan.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>计划描述</el-divider>
        <p style="line-height: 1.6; color: #666;">{{ currentViewPlan.description || '暂无描述' }}</p>

        <el-divider>年度目标</el-divider>
        <p style="line-height: 1.6; color: #666; white-space: pre-wrap;">{{ currentViewPlan.objectives || '暂无目标' }}</p>
      </div>

      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="editPlan(currentViewPlan)">编辑此计划</el-button>
        <el-button type="success" @click="generateMonthlyPlansForAnnual(currentViewPlan)" icon="MagicStick">
          生成月度建议
        </el-button>
      </template>
    </el-dialog>

    <!-- 重新生成月度建议确认对话框 -->
    <el-dialog
      v-model="showMonthlyGenerationConfirmDialog"
      title="生成月度计划建议"
      width="600px"
    >
      <div v-if="selectedAnnualPlanForMonthly">
        <el-alert
          title="提示"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          系统将基于以下年度计划生成12个月的月度计划建议：
        </el-alert>

        <el-descriptions :column="1" border>
          <el-descriptions-item label="年度计划">
            {{ selectedAnnualPlanForMonthly.year }}年 - {{ selectedAnnualPlanForMonthly.title }}
          </el-descriptions-item>
          <el-descriptions-item label="计划描述">
            {{ selectedAnnualPlanForMonthly.description }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />
        <p style="color: #909399; font-size: 14px;">
          <el-icon><InfoFilled /></el-icon>
          生成后，您可以在月度计划页面中查看、编辑和选择性创建这些建议。
        </p>
      </div>

      <template #footer>
        <el-button @click="showMonthlyGenerationConfirmDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmGenerateMonthlyPlans"
          :loading="generatingMonthlyPlans"
          icon="MagicStick"
        >
          确认生成
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted, h, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import { 
  Plus, 
  MagicStick, 
  Delete, 
  Clock, 
  Loading, 
  SuccessFilled,
  Search,
  View,
  Edit,
  InfoFilled
} from '@element-plus/icons-vue'

export default {
  name: 'AnnualPlans',
  components: {
    Plus,
    MagicStick,
    Delete,
    Clock,
    Loading,
    SuccessFilled,
    Search,
    View,
    Edit,
    InfoFilled
  },
  emits: ['create-plan'],
  setup(props, { emit }) {
    const authStore = useAuthStore()
    const annualPlans = ref([])
    const loading = ref(false)
    const showCreateDialog = ref(false)
    const showAISuggestionDialog = ref(false)
    const showAIConfirmDialog = ref(false)
    const editingPlan = ref(null)
    const submitting = ref(false)
    const generatingAISuggestion = ref(false)
    const selectedPlans = ref([])
    const aiSuggestionResult = ref(null)
    const aiSuggestionError = ref('')
    
    // 筛选和搜索相关
    const filterYear = ref('')
    const filterStatus = ref('')
    const searchTitle = ref('')
    
    const planForm = ref({
      year: new Date().getFullYear(),
      title: '',
      description: '',
      objectives: ''
    })

    const aiSuggestionForm = ref({
      goal: '',
      keyMetrics: '',
      timeframe: null
    })
    
    // 查看详情相关
    const showDetailDialog = ref(false)
    const currentViewPlan = ref(null)
    
    // 重新生成月度建议相关
    const showMonthlyGenerationConfirmDialog = ref(false)
    const selectedAnnualPlanForMonthly = ref(null)
    const generatingMonthlyPlans = ref(false)
    // 流式生成相关
    const isGeneratingStream = ref(false)
    const generationProgress = ref(0)
    const generationTotal = ref(12)
    const generationStatus = ref('') // '正在初始化...', '正在生成 2024-01...', '生成完成'
    
    const planFormRef = ref(null)
    
    const rules = {
      year: [{ required: true, message: '请选择年份', trigger: 'blur' }],
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
    }

    // 计算可用年份列表
    const availableYears = computed(() => {
      if (annualPlans.value.length === 0) return []
      const years = annualPlans.value.map(plan => plan.year)
      return [...new Set(years)].sort((a, b) => b - a)
    })

    // 筛选后的计划列表
    const filteredPlans = computed(() => {
      let result = annualPlans.value

      // 按年份筛选
      if (filterYear.value) {
        result = result.filter(plan => plan.year === filterYear.value)
      }

      // 按状态筛选
      if (filterStatus.value) {
        result = result.filter(plan => plan.status === filterStatus.value)
      }

      // 按标题搜索
      if (searchTitle.value.trim()) {
        const searchText = searchTitle.value.toLowerCase()
        result = result.filter(plan => 
          plan.title.toLowerCase().includes(searchText) ||
          (plan.description && plan.description.toLowerCase().includes(searchText))
        )
      }

      return result
    })

    // 应用筛选（防抖处理已通过v-model实现）
    const applyFilters = () => {
      // 筛选逻辑通过computed自动处理
    }

    // 清除筛选条件
    const clearFilters = () => {
      filterYear.value = ''
      filterStatus.value = ''
      searchTitle.value = ''
    }

    // 创建计划（支持快捷键）
    const handleCreate = () => {
      emit('create-plan')
    }

    // 双击行编辑
    const handleRowDblClick = (row) => {
      editPlan(row)
    }

    // 批量操作命令处理
    const handleBatchCommand = (command) => {
      switch (command) {
        case 'complete':
          batchUpdateStatus('completed')
          break
        case 'in_progress':
          batchUpdateStatus('in_progress')
          break
        case 'pending':
          batchUpdateStatus('pending')
          break
        case 'delete':
          batchDelete()
          break
      }
    }

    // 批量更新状态
    const batchUpdateStatus = async (status) => {
      if (selectedPlans.value.length === 0) {
        ElMessage.warning('请先选择要操作的计划')
        return
      }

      const statusText = getStatusText(status)
      try {
        await ElMessageBox.confirm(
          `确定要将选中的 ${selectedPlans.value.length} 个计划标记为"${statusText}"吗？`,
          '确认批量更新',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )

        let successCount = 0
        let failCount = 0
        const errors = []

        for (const plan of selectedPlans.value) {
          try {
            await axios.put(
              `/api/plans/annual/${plan.id}/status`,
              { status },
              { headers: { Authorization: `Bearer ${authStore.token}` } }
            )
            successCount++
          } catch (error) {
            failCount++
            errors.push(`${plan.title}: ${error.response?.data?.error || error.message}`)
          }
        }

        if (successCount > 0) {
          ElMessage.success(`成功更新 ${successCount} 个计划`)
          fetchAnnualPlans()
        }
        
        if (failCount > 0) {
          ElMessage.error({
            message: `${failCount} 个计划更新失败`,
            duration: 5000
          })
          console.error('批量更新失败详情:', errors)
        }

        selectedPlans.value = []
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量更新错误:', error)
        }
      }
    }

    // 键盘快捷键支持
    const handleKeydown = (event) => {
      // Ctrl+N 或 Cmd+N 创建新计划
      if ((event.ctrlKey || event.metaKey) && event.key === 'n') {
        event.preventDefault()
        handleCreate()
      }
      // Esc 关闭对话框
      if (event.key === 'Escape') {
        if (showCreateDialog.value) showCreateDialog.value = false
        if (showAISuggestionDialog.value) showAISuggestionDialog.value = false
        if (showAIConfirmDialog.value) showAIConfirmDialog.value = false
      }
    }
    
    const fetchAnnualPlans = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/plans/annual', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        annualPlans.value = response.data
      } catch (error) {
        ElMessage.error('获取年度计划失败')
      } finally {
        loading.value = false
      }
    }
    
    const submitPlan = async () => {
      if (!planFormRef.value) return
      
      await planFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            const url = editingPlan.value 
              ? `/api/plans/annual/${editingPlan.value.id}`
              : '/api/plans/annual'
            
            const method = editingPlan.value ? 'put' : 'post'
            
            await axios({
              method,
              url,
              data: planForm.value,
              headers: { Authorization: `Bearer ${authStore.token}` }
            })
            
            ElMessage.success(editingPlan.value ? '更新成功' : '创建成功')
            showCreateDialog.value = false
            resetForm()
            fetchAnnualPlans()
          } catch (error) {
            ElMessage.error('操作失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    const editPlan = (plan) => {
      editingPlan.value = plan
      planForm.value = {
        year: plan.year,
        title: plan.title,
        description: plan.description,
        objectives: plan.objectives
      }
      showCreateDialog.value = true
    }
    
    const toggleStatus = async (plan) => {
      const newStatus = plan.status === 'completed' ? 'pending' : 'completed'
      try {
        await axios.put(
          `/api/plans/annual/${plan.id}/status`,
          { status: newStatus },
          { headers: { Authorization: `Bearer ${authStore.token}` } }
        )
        ElMessage.success('状态更新成功')
        fetchAnnualPlans()
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    const deletePlan = async (plan) => {
      try {
        await ElMessageBox.confirm(
          h('div', [
            h('p', `确定要删除年度计划 "${plan.title}" 吗？`),
            h('p', { style: 'color: #E6A23C; margin-top: 10px; font-weight: bold;' }, 
              '⚠️ 此操作将同时删除：'),
            h('ul', { style: 'margin: 5px 0; padding-left: 20px; color: #E6A23C;' }, [
              h('li', '所有关联的月度计划'),
              h('li', '所有关联的周计划'),
              h('li', '相关的进度数据')
            ]),
            h('p', { style: 'color: #F56C6C; margin-top: 10px; font-weight: bold;' }, 
              '此操作不可恢复！')
          ]),
          '确认删除',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false
          }
        )
        
        await axios.delete(`/api/plans/annual/${plan.id}`, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        ElMessage.success('删除成功')
        fetchAnnualPlans()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const batchDelete = async () => {
      if (selectedPlans.value.length === 0) {
        ElMessage.warning('请先选择要删除的计划')
        return
      }

      try {
        await ElMessageBox.confirm(
          h('div', [
            h('p', { style: 'font-size: 16px; font-weight: bold;' }, 
              `确定要删除选中的 ${selectedPlans.value.length} 个年度计划吗？`),
            h('p', { style: 'color: #909399; margin: 10px 0;' }, 
              '以下计划将被删除：'),
            h('ul', { style: 'margin: 5px 0; padding-left: 20px; max-height: 200px; overflow-y: auto;' }, 
              selectedPlans.value.map(plan => 
                h('li', { style: 'margin: 5px 0;' }, `${plan.year}年 - ${plan.title}`)
              )
            ),
            h('p', { style: 'color: #E6A23C; margin-top: 15px; font-weight: bold;' }, 
              '⚠️ 此操作将同时删除所有关联的月度计划、周计划和相关数据'),
            h('p', { style: 'color: #F56C6C; margin-top: 10px; font-weight: bold;' }, 
              '此操作不可恢复！')
          ]),
          '确认批量删除',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'error',
            dangerouslyUseHTMLString: false
          }
        )

        let successCount = 0
        let failCount = 0
        const errors = []

        // 逐个删除以便提供详细反馈
        for (const plan of selectedPlans.value) {
          try {
            await axios.delete(`/api/plans/annual/${plan.id}`, {
              headers: { Authorization: `Bearer ${authStore.token}` }
            })
            successCount++
          } catch (error) {
            failCount++
            errors.push(`${plan.title}: ${error.response?.data?.error || error.message}`)
          }
        }

        if (successCount > 0) {
          ElMessage.success(`成功删除 ${successCount} 个年度计划`)
          fetchAnnualPlans()
        }
        
        if (failCount > 0) {
          ElMessage.error({
            message: `${failCount} 个计划删除失败`,
            duration: 5000
          })
          console.error('批量删除失败详情:', errors)
        }

        selectedPlans.value = []
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const handleSelectionChange = (selection) => {
      selectedPlans.value = selection
    }
    
    const resetForm = () => {
      editingPlan.value = null
      planForm.value = {
        year: new Date().getFullYear(),
        title: '',
        description: '',
        objectives: ''
      }
    }
    
    const getStatusType = (status) => {
      const types = {
        pending: 'info',
        in_progress: 'warning',
        completed: 'success'
      }
      return types[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const texts = {
        pending: '待开始',
        in_progress: '进行中',
        completed: '已完成'
      }
      return texts[status] || status
    }

    const createMonthlyPlansFromAnnual = async (monthlyPlans) => {
      try {
        let successCount = 0
        let errorCount = 0
        
        for (const monthPlan of monthlyPlans) {
          try {
            const [year, month] = monthPlan.month.split('-')
            
            // 构建任务描述
            const tasksDescription = monthPlan.tasks?.map(task => 
              `${task.title}（${task.priority}优先级，预计${task.estimatedHours}小时）`
            ).join('；') || ''
            
            // 构建指标描述
            let metricsDescription = ''
            if (monthPlan.metrics && Array.isArray(monthPlan.metrics)) {
               metricsDescription = monthPlan.metrics.map(m => `${m.name}: ${m.target}`).join('；')
            } else {
               metricsDescription = monthPlan.keyMetrics?.join('；') || ''
            }
            
            await axios.post('/api/plans/monthly', {
              year: parseInt(year),
              month: parseInt(month),
              title: monthPlan.title || `${month}月工作计划`,
              description: tasksDescription || '暂无具体任务描述',
              objectives: metricsDescription || '暂无关键指标',
              status: 'pending'
            }, {
              headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
            })
            
            successCount++
            
            // 添加小延迟避免请求过于频繁
            await new Promise(resolve => setTimeout(resolve, 100))
            
          } catch (error) {
            console.error(`创建 ${monthPlan.month} 月度计划失败:`, error)
            errorCount++
          }
        }
        
        if (successCount > 0) {
          ElMessage.success(`成功创建 ${successCount} 个月度计划`)
        }
        if (errorCount > 0) {
          ElMessage.warning(`${errorCount} 个月度计划创建失败，请手动检查`)
        }
        
      } catch (error) {
        console.error('创建月度计划总体失败:', error)
        ElMessage.error('月度计划创建失败，请手动创建')
      }
    }

    const generateAISuggestion = async () => {
      if (!aiSuggestionForm.value.goal.trim()) {
        ElMessage.error('请输入工作目标')
        return
      }

      generatingAISuggestion.value = true
      aiSuggestionError.value = ''
      try {
        const response = await axios.post('/api/ai-suggestions/annual-breakdown', {
          goal: aiSuggestionForm.value.goal,
          keyMetrics: aiSuggestionForm.value.keyMetrics,
          year: new Date().getFullYear()
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        // 检查是否有AI错误信息
        if (response.data.aiError) {
          aiSuggestionError.value = response.data.aiError
          ElMessage.warning('AI服务暂时不可用，已使用默认计划模板')
        }

        // 保存AI建议结果
        aiSuggestionResult.value = response.data
        showAISuggestionDialog.value = false
        showAIConfirmDialog.value = true

      } catch (error) {
        console.error('AI建议生成错误:', error)
        if (error.response) {
          ElMessage.error(`AI建议生成失败: ${error.response.data.error || '服务器错误'}`)
        } else if (error.request) {
          ElMessage.error('网络连接失败，请检查网络连接')
        } else {
          ElMessage.error('AI建议生成失败，请稍后重试')
        }
      } finally {
        generatingAISuggestion.value = false
      }
    }

    const confirmAISuggestion = async () => {
      const aiPlan = aiSuggestionResult.value
      
      // 情况1：基于已有年度计划生成月度计划（流式生成）
      if (!aiPlan.annualPlan && aiPlan.monthlyPlans) {
        await createMonthlyPlansFromAnnual(aiPlan.monthlyPlans)
        showAIConfirmDialog.value = false
        ElMessage.success('已根据AI建议自动创建了月度计划')
        return
      }
        
      // 情况2：全新生成年度计划
      // 生成年度计划描述
      const strategies = aiPlan.annualPlan.strategies?.join('；') || ''
      const outcomes = aiPlan.annualPlan.expectedOutcomes?.join('；') || ''
      
      planForm.value = {
        year: new Date().getFullYear(),
        title: aiPlan.annualPlan.title,
        description: aiPlan.annualPlan.objective,
        objectives: `战略措施：${strategies}\n预期成果：${outcomes}`
      }

      // 自动创建月度计划
      await createMonthlyPlansFromAnnual(aiPlan.monthlyPlans)

      showAIConfirmDialog.value = false
      showCreateDialog.value = true
      ElMessage.success('AI年度计划建议已确认，并自动创建了12个月度计划')
    }

    const regenerateAISuggestion = async () => {
      showAIConfirmDialog.value = false
      showAISuggestionDialog.value = true
      // 保留原有的目标和关键指标，用户可以修改
    }

    // 查看年度计划详情
    const viewPlanDetail = (plan) => {
      currentViewPlan.value = plan
      showDetailDialog.value = true
    }

    // 为年度计划生成月度建议
    const generateMonthlyPlansForAnnual = (plan) => {
      selectedAnnualPlanForMonthly.value = plan
      showMonthlyGenerationConfirmDialog.value = true
    }

    // 确认生成月度计划
    const confirmGenerateMonthlyPlans = async () => {
      if (!selectedAnnualPlanForMonthly.value) return

      generatingMonthlyPlans.value = true
      try {
        const year = selectedAnnualPlanForMonthly.value.year
        
        // 构建prompt
        const prompt = `请将以下年度工作计划分解为月度计划：

年度目标：${selectedAnnualPlanForMonthly.value.title}
详细描述：${selectedAnnualPlanForMonthly.value.description || ''}
年度目标：${selectedAnnualPlanForMonthly.value.objectives || ''}

请为${year}年的每个月生成详细的工作计划。`

        // 设置时间范围（整个年度）
        const timeframe = [
          `${year}-01`,
          `${year}-12`
        ]
        
        const response = await axios.post('/api/ai-suggestions/monthly-breakdown', {
          prompt,
          timeframe
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        // 将结果保存到AI建议结果中
        aiSuggestionResult.value = response.data
        
        // 关闭当前确认对话框，打开AI建议确认对话框
        showMonthlyGenerationConfirmDialog.value = false
        showDetailDialog.value = false
        showAIConfirmDialog.value = true

        ElMessage.success('月度计划建议已生成！请查看并选择要创建的月度计划')
      } catch (error) {
        console.error('生成月度建议失败:', error)
        if (error.response) {
          ElMessage.error(`生成失败: ${error.response.data.error || '服务器错误'}`)
        } else {
          ElMessage.error('生成月度建议失败，请稍后重试')
        }
      } finally {
        generatingMonthlyPlans.value = false
      }
    }
    
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    onMounted(() => {
      fetchAnnualPlans()
      // 添加键盘事件监听
      window.addEventListener('keydown', handleKeydown)
    })

    onUnmounted(() => {
      // 移除键盘事件监听
      window.removeEventListener('keydown', handleKeydown)
    })
    
    return {
      annualPlans,
      filteredPlans,
      selectedPlans,
      loading,
      showCreateDialog,
      showAISuggestionDialog,
      showAIConfirmDialog,
      editingPlan,
      submitting,
      generatingAISuggestion,
      aiSuggestionError,
      planForm,
      aiSuggestionForm,
      aiSuggestionResult,
      planFormRef,
      rules,
      filterYear,
      filterStatus,
      searchTitle,
      availableYears,
      applyFilters,
      clearFilters,
      handleCreate,
      handleRowDblClick,
      handleBatchCommand,
      batchUpdateStatus,
      submitPlan,
      editPlan,
      toggleStatus,
      deletePlan,
      batchDelete,
      handleSelectionChange,
      generateAISuggestion,
      confirmAISuggestion,
      regenerateAISuggestion,
      getStatusType,
      getStatusText,
      formatDate,
      // 查看详情相关
      showDetailDialog,
      currentViewPlan,
      viewPlanDetail,
      // 重新生成月度建议相关
      showMonthlyGenerationConfirmDialog,
      selectedAnnualPlanForMonthly,
      generatingMonthlyPlans,
      generateMonthlyPlansForAnnual,
      confirmGenerateMonthlyPlans
    }
  }
}
</script>

<style scoped>
.annual-plans-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.filter-section {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  flex: 1;
  min-width: 400px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.text-content {
  word-break: break-word;
  line-height: 1.4;
  max-height: 3.2em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.ai-confirm-content {
  max-height: 600px;
  overflow-y: auto;
}

.ai-confirm-content h4 {
  margin: 15px 0 10px 0;
  color: #333;
}

.ai-confirm-content ul {
  margin: 0;
  padding-left: 20px;
}

.ai-confirm-content li {
  margin-bottom: 5px;
  line-height: 1.4;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-section {
    min-width: 100%;
  }
  
  .action-buttons {
    justify-content: center;
  }
}
</style>
